package com.epfresh.supplier.adapter;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.Goods;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import multitype.ItemViewBinder;
import multitype.OnRecyclerViewItemClickListener;
import com.epfresh.api.global.*;


public class GoodsListViewBinder extends ItemViewBinder<Goods, GoodsListViewBinder.ViewHolder> implements View.OnClickListener {

    OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
    OnUpdateListener onUpdateListener;
    OnGroupListener onGroupListener;
    OnTextChangerListener onTextChangerListener;

    public OnTextChangerListener getOnTextChangerListener() {
        return onTextChangerListener;
    }

    public void setOnTextChangerListener(OnTextChangerListener onTextChangerListener) {
        this.onTextChangerListener = onTextChangerListener;
    }

    public OnGroupListener getOnGroupListener() {
        return onGroupListener;
    }

    public void setOnGroupListener(OnGroupListener onGroupListener) {
        this.onGroupListener = onGroupListener;
    }

    public OnUpdateListener getOnUpdateListener() {
        return onUpdateListener;
    }

    public void setOnUpdateListener(OnUpdateListener onUpdateListener) {
        this.onUpdateListener = onUpdateListener;
    }

    public OnRecyclerViewItemClickListener getOnRecyclerViewItemClickListener() {
        return onRecyclerViewItemClickListener;
    }

    public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }

    //更新某个位置的数据
    public void notifyItem(int position) {
        if (position > -1 && position < getAdapter().getItemCount())
            getAdapter().notifyItemChanged(position);
    }

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(
            @NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View view = inflater.inflate(R.layout.item_category_goods, parent, false);
        return new ViewHolder(view);
    }


    @Override
    protected void onBindViewHolder(@NonNull ViewHolder holder, @NonNull Goods post) {

        int position = getPosition(holder);
/*        holder.tvUpdate.setTag(R.id.item_key_position, position);
        holder.tvUpdate.setTag(R.id.item_key_status, post);
        holder.tvUpdate.setOnClickListener(this);
        holder.tvUpdateInfo.setTag(R.id.item_key_position, position);
        holder.tvUpdateInfo.setTag(R.id.item_key_status, post);
        holder.tvUpdateInfo.setOnClickListener(this);*/
        holder.tvGroup.setTag(R.id.item_key_position, position);
        holder.tvGroup.setTag(R.id.item_key_status, post);
        holder.tvGroup.setOnClickListener(this);

        holder.ivMinus.setTag(R.id.item_key_position, position);
        holder.ivMinus.setTag(R.id.item_key_status, post);
        holder.ivMinus.setOnClickListener(this);
        holder.ivAdd.setTag(R.id.item_key_position, position);
        holder.ivAdd.setTag(R.id.item_key_status, post);
        holder.ivAdd.setOnClickListener(this);

        holder.etPrice.setTag(position);

        holder.etPrice.setTag(R.id.item_key_position, position);
        holder.etPrice.setTag(R.id.item_key_status, post);
        holder.etPrice.addTextChangedListener(new AttTextWatcher(holder));

        int itemCount = getAdapter().getItemCount();

        holder.setData(post);
        if (itemCount -2 == position){
            holder.vUpdateBg.setVisibility(View.GONE);
        }else {
            holder.vUpdateBg.setVisibility(View.VISIBLE);
        }


    }

    @Override
    public void onClick(View v) {

        Object tag = v.getTag(R.id.item_key_position);
        if (tag != null && tag instanceof Integer){
            int position = (int) tag;
            Object o = v.getTag(R.id.item_key_status);

          if (v.getId() == R.id.tv_update_info || v.getId() == R.id.tv_update) {

                if (onUpdateListener != null) {
                    onUpdateListener.onUpdate(position, (Goods) o);
                }
          } else if (v.getId() == R.id.tv_group) {
              if (onGroupListener != null) {
                  onGroupListener.onGroup(position, (Goods) o);
              }

          } else if (onRecyclerViewItemClickListener != null && o instanceof Goods) {
              onRecyclerViewItemClickListener.onItemClick(v, position, o);
          }
        }
    }
    private class AttTextWatcher implements TextWatcher {

        ViewHolder holder = null;
        public AttTextWatcher(ViewHolder holder){
            this.holder = holder;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Goods goods = (Goods)holder.etPrice.getTag(R.id.item_key_status);

            if (TextUtils.isEmpty(s.toString())) {
                return;
            }
            try {
                Double.parseDouble(s.toString());//损失
            } catch (Exception ex) {
                return;
            }
            goods.setPriceNow(new BigDecimal(Double.parseDouble(s.toString())).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
            if(goods.getPriceNow()>99999.99){
                goods.setPriceNow(99999.99);
                T.toast("价格不能大于99999.99");
                getAdapter().notifyItemChanged(getPosition(holder));
            }


            DataManager.getInstance().putPriceGoods(goods.getId(),goods);
            if(!goods.getPrice().equals(goods.getPriceNow())){
                holder.etPrice.setTextColor(Color.RED);
            }else{
                DataManager.getInstance().removePriceGoods(goods.getId());
                holder.etPrice.setTextColor(0xff333333);
            }




            if (onTextChangerListener!=null)
                onTextChangerListener.onChange();
        }

    }

    static class ViewHolder extends RecyclerView.ViewHolder {


        ImageView iv;
        ImageView ivAdd;
        ImageView ivMinus;
        TextView tvTitle;
        TextView tvPackage;
        EditText etPrice;
        TextView tvInventory;
        TextView tvUnit;
        TextView tvGroup;

        TextView tv_sale_price_title;

/*        TextView tvUpdate;
        TextView tvUpdateInfo;*/
        View vUpdateBg;



        ViewHolder(@NonNull View itemView) {
            super(itemView);


            iv = (ImageView) itemView.findViewById(R.id.iv_info_img);
            ivAdd = (ImageView) itemView.findViewById(R.id.iv_add);
            ivMinus = (ImageView) itemView.findViewById(R.id.iv_minus);

            tv_sale_price_title = (TextView) itemView.findViewById(R.id.tv_sale_price_title);

            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvPackage = (TextView) itemView.findViewById(R.id.tv_package);
            tvInventory = (TextView) itemView.findViewById(R.id.tv_inventory);
            tvGroup = (TextView) itemView.findViewById(R.id.tv_group);
            tvUnit = (TextView) itemView.findViewById(R.id.tv_unit);
            /*tvUpdate = (TextView) itemView.findViewById(R.id.tv_update);
            tvUpdateInfo = (TextView) itemView.findViewById(R.id.tv_update_info);*/
            vUpdateBg = itemView.findViewById(R.id.v_update);
            etPrice = (EditText) itemView.findViewById(R.id.et_price);
            etPrice.setFilters(new InputFilter[]{new CashierInputFilter()});

        }
        void setData(Goods post) {
            String thumbnail = post.getThumbnail();
            ImageLoader.getInstance().displayImage(thumbnail, iv);
            tvTitle.setText(post.getTitle());
            tvPackage.setText(post.getPackStr());
            BigDecimal bigDecimal = new BigDecimal( post.getInventory());
            tvInventory.setText("库存"+FormatUtil.subZeroAndDot(bigDecimal.toString()));
            tvUnit.setText(post.getPriceUnitStr());
            if (BaseApplication.getInstance().isCategoryLevelOne()) {
                tv_sale_price_title.setText("销售价：");
            }else{
                tv_sale_price_title.setText("预计成本价：");
            }


            if(DataManager.getInstance().getPriceGoods(post.getId())!=null&&DataManager.getInstance().getPriceGoods(post.getId()).getPriceNow()!=post.getPrice()){
                etPrice.setText(FormatUtil.subZeroAndDot(""+DataManager.getInstance().getPriceGoods(post.getId()).getPriceNow()));
                etPrice.setTextColor(Color.RED);
            }else{
                etPrice.setText(FormatUtil.subZeroAndDot(""+post.getPrice()));
                etPrice.setTextColor(0xff333333);
            }

            if (!BaseApplication.getInstance().isCategoryLevelOne()) {
                /*tvUpdateInfo.setVisibility(View.GONE);
                tvUpdate.setVisibility(View.GONE);*/
                vUpdateBg.setVisibility(View.VISIBLE);
                tvGroup.setVisibility(View.VISIBLE);
                tvInventory.setVisibility(View.GONE);
            } else {
                tvGroup.setVisibility(View.GONE);
                tvInventory.setVisibility(View.VISIBLE);
                String message = post.getMessage();
                if (message == null || "".equals(message)) {
                   /* tvUpdateInfo.setVisibility(View.GONE);
                    tvUpdate.setVisibility(View.GONE);*/
                    vUpdateBg.setVisibility(View.GONE);
                } else {
/*                    tvUpdateInfo.setVisibility(View.VISIBLE);
                    tvUpdate.setVisibility(View.VISIBLE);*/
                    vUpdateBg.setVisibility(View.VISIBLE);
                }
/*                tvUpdateInfo.setText(message);
                tvUpdateInfo.setTextColor(post.getColorInt());*/
            }
        }
    }


    public interface OnUpdateListener {
        void onUpdate(int position, Goods goods);
    }
    public interface OnGroupListener {
        void onGroup(int position, Goods goods);
    }

    public interface OnTextChangerListener {
        void onChange();
    }


}
